package com.bountytask.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bountytask.entity.UserInfo;
import com.bountytask.service.LoginService;
import com.bountytask.service.impl.LoginServiceImpl;
import com.bountytask.util.JwtUtil;
import com.bountytask.util.RedisUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


@RestController
public class LoginController {
    Logger logger = LoggerFactory.getLogger(LoginController.class);
    @Autowired
    private LoginService loginService;

    @Autowired
    private RedisUtils redisUtils;

    private static final long EXPIRE_TIME = 1000 * 60 * 60 * 24 * 7;

    @PostMapping("/token")
    public JSONObject tokenLogin(@RequestParam String token){
        JSONObject resultJson = new JSONObject();
        resultJson.put("code",200);
        resultJson.put("message","成功");
        UserInfo user=JSONObject.parseObject(JwtUtil.getInfo(token),UserInfo.class);
        resultJson.put("data",JSON.parseObject(JwtUtil.getInfo(token),UserInfo.class));
        return resultJson;
    }

    //登录/注册
    @PostMapping("/login")
    public JSONObject wxLogin(@RequestBody JSONObject loginData){
        String code=loginData.getString("code");
        String encryptedData=loginData.getString("encryptedData");
        String iv=loginData.getString("iv");
        logger.info("code:" + code);
        String url="https://api.weixin.qq.com/sns/jscode2session?" +
                "appid=" + "wxff4e4c4a669de16c"+
                "&secret=" + "076d3496d6777fd61db7687a5b892f79"+
                "&js_code=" + code +
                "&grant_type=authorization_code";
        String jsonData = new RestTemplate().getForObject(url,String.class);
        JSONObject jsonObject=JSON.parseObject(jsonData);
        String openid = jsonObject.getString("openid");
        String sessionKey = jsonObject.getString("session_key");

        JSONObject resultJson=new JSONObject(true);
        if (StringUtils.contains(jsonData, "errcode")) {
            //出错了
            resultJson.put("code",400);
            resultJson.put("message","失败");
            return resultJson;
        }
        UserInfo user0 =loginService.getUserByOpenId(openid);
        JSONObject data = new JSONObject();
        if (user0==null){
            //解密
            String s=null;
            try {
                s=loginService.loginDecrypt(encryptedData,jsonObject,iv);
            } catch (Exception e) {
                e.printStackTrace();
            }
            JSONObject jsonObject1 = JSON.parseObject(s);
            Object watermark = jsonObject1.get("watermark");
            JSONObject jsonObject2 = JSON.parseObject(String.valueOf(watermark));
            jsonObject2.get("timestamp");
            jsonObject2.get("appid");

            //添加到数据库中
            UserInfo user = new UserInfo();
            user.setAvatarUrl(String.valueOf(jsonObject1.get("avatarUrl")));
            user.setNickName(String.valueOf(jsonObject1.get("nickName")));
            user.setOpenId(openid);
            user.setMoney(0);
            resultJson=loginService.register(user);

            //生成JWT字符串
            System.out.println(user.toString());
            String token= JwtUtil.sign(String.valueOf(user.getId()),JSON.toJSONString(user));

            data.put("token",token);
            data.put("user",user);
            resultJson.put("data",data);
            return resultJson;
        }

        //生成JWT字符串
        System.out.println(user0);
        String token= JwtUtil.sign(String.valueOf(user0.getId()),JSON.toJSONString(user0));
        //将token存在redis里
        redisUtils.set(token,user0.getId(),EXPIRE_TIME);
        resultJson.put("code",200);
        resultJson.put("message","成功");
        data.put("token",token);
        data.put("user",user0);
        resultJson.put("data",data);
        return resultJson;
    }
}
